let ErrorUtils = require('../utils/error/ErrorUtils');
let {Storage, Order} = require('../models');
const {infoLogger, errorLogger} = require('../config').logger;
const Joi = require('joi');
const perpage = 10;
const lodash = require('lodash');

class OrderService {
    /**
     * 获取订单列表
     * @returns {Promise<void>}
     */
    static async list(type) {
        infoLogger.info(">>>>>获取预约列表开始");
        infoLogger.info(">>>>>请求的type:" + type);
        let date = new Date();
        let query = Order.find();
        switch (type.toString()) {
            case '1':
                query.where("orderTime")
                    .gte(date);
                break;
            case '2':
                query.where("orderTime")
                    .lt(date);
                break;
            default:
        }
        query.populate({
            select: "username logo address",
            path: "storeId",
        }).populate({
            select: "username phone",
            path: "teacherId",
        });
        let result = await query.lean().exec();
        if (result) {
            for (let i = 0; i < result.length; i++) {
                if (result[i].orderTime > new Date()) {
                    result[i].type = 1;
                } else {
                    result[i].type = 2;
                }
            }
        }
        return result;
    }

    static checkOrderData(data) {
        let schema = Joi.object({
            userName: Joi.string().min(2).max(20).required(),
            phone: Joi.string().min(11).max(11).required(),
            storeName: Joi.string().min(2).max(30).required(),
            orderTime: Joi.number().min(0).required(),
            storeId: Joi.string().required(),
            teacherId: Joi.string().required(),
            teacher: Joi.string().required(),
            orderType: Joi.string().required(),
            address: Joi.string().required(),
            teacherPhone: Joi.string().required(),
        });
        let result = Joi.validate(data, schema);
        return result;
    }

    /**
     * 预约记录添加
     * @returns {Promise<*>}
     */
    static async create(data, userInfo) {
        infoLogger.info(">>>>>:预约记录添加开始");
        await OrderService.checkOrderData(data);
        data.userId = userInfo._id;
        data.openId = userInfo.openId;
        let result = await Order.findOne({
            userId: data.userId,
            teacherId: data.teacherId,
            storeId: data.storeId,
        }).lean().exec();
        if (!result) {
            return await Order.create(data);
        } else {
            let time = new Date(parseInt(data.orderTime));
            let hour = result.orderTime.getHours();
            let minute = result.orderTime.getMinutes();
            let time1 = time.getHours() + ":" + time.getMinutes();
            let time2 = hour + ":" + minute;
            if (time1 == time2) {
                ErrorUtils.throwApiError(ErrorUtils.ORDER_HAS_EXIST);
            } else {
                return await Order.create(data);
            }
        }
    }
    static async getOrderDetail(orderId){
        if(!orderId){
            ErrorUtils.throwApiError(ErrorUtils.ORDER_ID_NOT_EXIST);
        }
        return await order.findById(orderId)
    }

    /**
     * 获取订单列表
     * @returns {Promise<void>}
     */
    static async adminList(type,page) {
        infoLogger.info(">>>>>获取预约列表开始");
        infoLogger.info(">>>>>请求的type:" + type);
        let date = new Date();
        if (!page) {
            page = 1;
        }
        page = parseInt(page);
        if (isNaN(page)) {
            ErrorUtils.throwApiError(ErrorUtils.REQUEST_ERROR);
        }
        let skip = (page - 1) * perpage;
        let query = Order.find();
        switch (type.toString()) {
            case '1':
                query.where("orderTime")
                    .gte(date);
                break;
            case '2':
                query.where("orderTime")
                    .lt(date);
                break;
            default:
        }
        query.populate({
            select: "username logo address",
            path: "storeId",
        }).populate({
            select: "username phone",
            path: "teacherId",
        });
        let query1 = lodash.clone(query);
        let count =await query1.count();
        let result = await query
            .skip(skip)
            .limit(perpage)
            .lean().exec();
        if (result) {
            for (let i = 0; i < result.length; i++) {
                if (result[i].orderTime > new Date()) {
                    result[i].type = 1;
                } else {
                    result[i].type = 2;
                }
            }
        }
        return {count: count, data: result};
    }
}

module.exports = OrderService;
